package com.beiye.drivertransport.SubActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.android.frame.adapter.ViewHolder;
import com.android.frame.http.HttpListener;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.DaiKaoCourseBean;
import com.beiye.drivertransport.bean.DaiKaoSureBean;
import com.beiye.drivertransport.bean.DaikaoAndHavetestCourseBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.CustomView;
import com.beiye.drivertransport.view.LinePathView;
import com.beiye.drivertransport.view.LiumRadioGroup;
import com.beiye.drivertransport.view.MyListView;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//在线考试待考试卷
public class DaiKaoActivity extends TwoBaseAty {


    ImageView img_daikaoback;

    TextView tv_daikaoDate;//发布日期

    TextView tv_qptName;//试卷种类名称

    TextView tv_passScore;//及格分

    TextView tv_questionNo;//试卷题数

    TextView tv_totalScore;//总分

    TextView tv_qpName;//试卷名称

    TextView tv_shizhang;//时长

    TextView tv_sure;

    TextView tv_daikao10;

    TextView img_sign1;

    TextView tv_daikao5;

    ImageView id_show_camera_iv;

    ImageView id_show_camera_iv1;

    ImageView id_show_camera_iv2;

    MyListView lv_daikao;

    ScrollView scroll_view;
    private SubDaiKaoAdapter subDaiKaoAdapter;
    private int i;
    private int sn;

    private int qpsn;
    public ArrayList<DaikaoAndHavetestCourseBean.RowsBean> testlist = new ArrayList<>();
    private TextView mTextView;
    private CustomView customView;
    private PopupWindow mUserPopWindow;
    private TextView tv_usename;
    private TextView tv_id;
    private TextView tv_phone;
    private TimerTask timerTask;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) {

                timerTask = new TimerTask() {
                    int cnt = 0;

                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String stringTime = getStringTime(cnt++);
                                tv_daikao10.setText(stringTime);
                                SharedPreferences sp = getSharedPreferences("durationandformat",
                                        Context.MODE_PRIVATE);
                                String firstandtime1 = getStringTime(firsttime);
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString("format", stringTime);
                                edit.putString("firsttime", firstandtime1);
                                edit.commit();
                                LogUtils.e("format", stringTime);
                                LogUtils.e("firsttime1", firstandtime1);
                                //         LogUtils.e("duration", duration);

                                if (stringTime.equals(firstandtime1)) {
                                    timerTask.cancel();
                                    if (!DaiKaoActivity.this.isFinishing()) {
                                        showUserfirstPopwindow(stringTime);
                                    }

                                }
                            }
                        });
                    }
                };
                timer1.schedule(timerTask, 0, 1000);

            }
        }
    };
    private String orgName;
    private TextView tv_company;
    private String qptId;
    private Timer timer1;
    private int firsttime;
    private int subformatTurnSecond;
    private int firsttime1;
    private PopupWindow mUserSecondPopWindow;
    private int subformatTurnThird;

    TextView tv_violation1;//重签

    LinePathView signatureview;//签字
    final File fileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Signname");
    //  private static final int REQUEST_EXTERNAL_STORAGE = 1;
//    private static String[] PERMISSIONS_STORAGE = {
//            "android.permission.READ_EXTERNAL_STORAGE",
//            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private ProgressDialog mProgressDialog;
    private int subformatTurnFour;
    private String paperSource;
    private PopupWindow mUserOnePopWindow;

    @Override
    public int getLayoutId() {
        return R.layout.activity_dai_kao;

    }


    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_daikaoback) {
            TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
            builder.setMessage("点放弃,将自动放弃这次考试记录");
            builder.setTitle("提示:");
            builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask = null;
                    timer1 = null;
                    dialog.dismiss();
                    SharedPreferences spp = getSharedPreferences("durationandformat",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit1 = spp.edit();
                    edit1.clear();
                    edit1.commit();
                    SharedPreferences sp = getSharedPreferences("score",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                    finish();
                    //设置你的操作事项
                }
            });

            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            builder.create().show();
        } else if (id == R.id.tv_violation1) {//    img_sign1.setVisibility(View.GONE);
            signatureview.clear();

            //        case R.id.img_sign1://签名提示
//            img_sign1.setVisibility(View.GONE);
//
//            break;
        } else if (id == R.id.tv_daikao6) {
            if (Utils.isFastClicker()) {
                return;
            }
            SharedPreferences sp = getSharedPreferences("durationandformat",
                    Context.MODE_PRIVATE);
            String format = sp.getString("format", "");
            int qpLength = sp.getInt("qpLength", 0);
            int qpLengthtime = qpLength * 60;
            String[] splitformat = format.split(":");
            String format1 = splitformat[0];
            String format2 = splitformat[1];
            String format3 = splitformat[2];
            int iformat1 = Integer.valueOf(format1);//转int
            int iformat2 = Integer.valueOf(format2);//转int
            int iformat3 = Integer.valueOf(format3);//转int
            int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
            if (formattime <= firsttime1)//第二次拍照后就可以提交第三张照片
            {
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                builder1.setMessage("还未到交卷时间，请检查您的答案无误之后再提交。");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                    }
                });

                builder1.create().show();
                return;
            }
            Drawable id_show_camera_iv2Drawable = id_show_camera_iv2.getDrawable();
            if (id_show_camera_iv2Drawable == null) {
                timerTask.cancel();
                SharedPreferences sp1 = getSharedPreferences("durationandformat",
                        Context.MODE_PRIVATE);
                String stringTime = sp1.getString("format", "");
                showUserthreePopwindow(stringTime);
            } else {

                if (formattime == qpLengthtime) {
                    if (qptId.equals("102005")) {
                        try {
                            //检测是否有写的权限
                            int permission = ActivityCompat.checkSelfPermission(DaiKaoActivity.this,
                                    "android.permission.WRITE_EXTERNAL_STORAGE");
                            if (permission != PackageManager.PERMISSION_GRANTED) {
                                ToastUtil.showShortToast(DaiKaoActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        save(fileDir);


                    } else {

                        try {
                            //检测是否有写的权限
                            int permission = ActivityCompat.checkSelfPermission(DaiKaoActivity.this,
                                    "android.permission.WRITE_EXTERNAL_STORAGE");
                            if (permission != PackageManager.PERMISSION_GRANTED) {
                                ToastUtil.showShortToast(DaiKaoActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        saveSecond(fileDir);
                        // showLoadingDialog("提交中");
                        // new Login().getDaikaoSure(sn,this,2);
                    }
                } else {
                    if (qptId.equals("102005")) {
                        for (int i = 0; i < testlist.size(); i++) {
                            if (testlist.get(i).isSelect() == false) {
                                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                                builder1.setMessage("第" + testlist.get(i).getSeqNo() + "题没有做");
                                builder1.setTitle("提示:");
                                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        ;
                                        //设置你的操作事项
                                    }
                                });
                                builder1.create().show();


                                return;
                            }
                        }

                        try {
                            //检测是否有写的权限
                            int permission = ActivityCompat.checkSelfPermission(DaiKaoActivity.this,
                                    "android.permission.WRITE_EXTERNAL_STORAGE");
                            if (permission != PackageManager.PERMISSION_GRANTED) {
                                ToastUtil.showShortToast(DaiKaoActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        save(fileDir);

                    } else {
                        for (int i = 0; i < testlist.size(); i++) {
                            if (testlist.get(i).isSelect() == false) {
                                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                                builder1.setMessage("第" + testlist.get(i).getSeqNo() + "题没有做");
                                builder1.setTitle("提示:");
                                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        ;
                                        //设置你的操作事项
                                    }
                                });
                                builder1.create().show();
                                return;
                            }
                        }
                        try {
                            //检测是否有写的权限
                            int permission = ActivityCompat.checkSelfPermission(DaiKaoActivity.this,
                                    "android.permission.WRITE_EXTERNAL_STORAGE");
                            if (permission != PackageManager.PERMISSION_GRANTED) {
                                ToastUtil.showShortToast(DaiKaoActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        saveSecond(fileDir);
                        // showLoadingDialog("提交中");
                        // new Login().getDaikaoSure(sn,this,2);
                    }
                }


            }
        }
    }

    @Override
    public void onBackPressed() {

        TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
        builder.setMessage("点放弃,将自动放弃这次考试记录");
        builder.setTitle("提示:");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                timerTask.cancel();
                timer1.cancel();
                timerTask = null;
                timer1 = null;
                dialog.dismiss();
                SharedPreferences sp = getSharedPreferences("score",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                SharedPreferences spp = getSharedPreferences("durationandformat",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit1 = spp.edit();
                edit1.clear();
                edit1.commit();
                finish();
                //设置你的操作事项
            }
        });

        builder.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
        //   super.onBackPressed();
    }

    private String getStringTime(int cnt) {
        int hour = cnt / 3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
    }

    @Override
    public void initData() {
        img_daikaoback = (ImageView) findViewById(R.id.img_daikaoback);
        tv_daikaoDate = (TextView) findViewById(R.id.tv_daikao);
        tv_qptName = (TextView) findViewById(R.id.tv_daikao1);
        tv_passScore = (TextView) findViewById(R.id.tv_daikao2);
        tv_questionNo = (TextView) findViewById(R.id.tv_daikao3);
        tv_totalScore = (TextView) findViewById(R.id.tv_daikao7);
        tv_qpName = (TextView) findViewById(R.id.tv_daikao4);
        tv_shizhang = (TextView) findViewById(R.id.tv_daikao8);
        tv_sure = (TextView) findViewById(R.id.tv_daikao6);
        tv_daikao10 = (TextView) findViewById(R.id.tv_daikao10);
        img_sign1 = (TextView) findViewById(R.id.img_sign1);
        tv_daikao5 = (TextView) findViewById(R.id.tv_daikao5);
        id_show_camera_iv = (ImageView) findViewById(R.id.id_show_camera_iv);
        id_show_camera_iv1 = (ImageView) findViewById(R.id.id_show_camera_iv1);
        id_show_camera_iv2 = (ImageView) findViewById(R.id.id_show_camera_iv2);
        lv_daikao = (MyListView) findViewById(R.id.listview_daikaotest);
        scroll_view = (ScrollView) findViewById(R.id.scroll_view);
        tv_violation1 = (TextView) findViewById(R.id.tv_violation1);
        signatureview = (LinePathView) findViewById(R.id.signatureview);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        //   verifyStoragePermissions(DaiKaoActivity.this);
        timer1 = new Timer();
        firsttime = 0;//第一次拍照1秒
        firsttime1 = (int) (60 + Math.random() * (120 - 60 + 1));//第二次拍照随机60秒到120秒
        Bundle bundle = getIntent().getExtras();
        //通过name关键字取出用户名
        sn = bundle.getInt("daikaosn");
        orgName = bundle.getString("orgName");
        qptId = bundle.getString("qptId");
        paperSource = bundle.getString("paperSource");
        Long daikaocreation = bundle.getLong("daikaocreation");
        qpsn = bundle.getInt("daikaoqpsn");
        Date date = new Date(daikaocreation);
        String time = "";
        try {
            //yyyy表示年MM表示月dd表示日
            //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            //进行格式化
            time = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_daikaoDate.setText("发布日期: " + time);

        if (paperSource.equals("ad")) {
            tv_daikao5.setText("试卷由区划发布");
        } else if (paperSource.equals("org")) {
            tv_daikao5.setText("试卷由企业发布");
        }

        customView = (CustomView) findViewById(R.id.customView);

        //  customView.invalidate();

        mTextView = (TextView) findViewById(R.id.letter_Tv);

        this.customView.setOnTouchMyLister(new CustomView.OnTouchLister() {
            @Override
            public void onTouch(int s) {
                mTextView.removeCallbacks(action);
                mTextView.setText(s + "");
                mTextView.setVisibility(View.VISIBLE);
                if (1 == s) {
                    lv_daikao.setSelection(0);
                }
                for (int i = 0; i <= testlist.size(); i++) {
                    int seqNo = testlist.get(i).getSeqNo();
                    if (seqNo == s) {
                        //    lv_daikao.setAdapter(subDaiKaoAdapter);
                        lv_daikao.requestFocusFromTouch();
                        lv_daikao.setSelection(i);

                        break;
                    }
                }
            }

            @Override
            public void up() {
                mTextView.postDelayed(action, 1500);
            }
        });


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                mHandler.sendEmptyMessage(0);
            }
        });
        thread.start();


    }


    //个人信息弹窗展示
    private void showUserfirstPopwindow(final String stringTime) {
        //    final  String firsttimesub = stringTime.substring(3, 8);//截取字符串00:00:00变成00:00
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        new Login().getUser(userId, this, 4);
        //设置contentView
        View contentView = LayoutInflater.from(DaiKaoActivity.this).inflate(R.layout.user_popwindowlayout, null);
        mUserPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture);//跟布局
        ImageView img_sure = (ImageView) contentView.findViewById(R.id.img_photo1);//确定
        ImageView img_no = (ImageView) contentView.findViewById(R.id.img_photo2);//取消
        tv_company = (TextView) contentView.findViewById(R.id.tv_photo8);
        tv_usename = (TextView) contentView.findViewById(R.id.tv_photo9);
        tv_phone = (TextView) contentView.findViewById(R.id.tv_photo10);
        tv_id = (TextView) contentView.findViewById(R.id.tv_photo11);
        mUserPopWindow.setFocusable(false);
        mUserPopWindow.setOutsideTouchable(false);
        mUserPopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);

        img_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUserPopWindow.dismiss();
                showUseronePopwindow(stringTime);
//                Bundle bundle = new Bundle();
//                bundle.putInt("daikaosn", sn);
//                bundle.putString("snapTime", firsttimesub);
//                startActivityForResult(TakePhotoScrollsActivity.class,bundle, 0);
            }
        });
        img_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mUserPopWindow.dismiss();
                timerTask.cancel();
                timer1.cancel();
                timerTask = null;
                timer1 = null;
                SharedPreferences sp = getSharedPreferences("score",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                SharedPreferences spp = getSharedPreferences("durationandformat",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit1 = spp.edit();
                edit1.clear();
                edit1.commit();
                finish();
            }
        });


    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        if (mUserPopWindow != null && mUserPopWindow.isShowing()) {
            return false;
        } else if (mUserOnePopWindow != null && mUserOnePopWindow.isShowing()) {
            return false;
        } else if (mUserSecondPopWindow != null && mUserSecondPopWindow.isShowing()) {
            return false;
        }

        return super.dispatchTouchEvent(event);
    }

    Runnable action = new Runnable() {
        public void run() {
            mTextView.setVisibility(View.GONE);
        }
    };

    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }
        String url = data.getStringExtra("url");
        // 根据返回码的不同，设置参数
        if (requestCode == 0) {
            if (resultCode == 1) {
                if (url != null && !TextUtils.isEmpty(url)) {
                    id_show_camera_iv.setContentDescription(url);
                    Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
                    id_show_camera_iv.setImageBitmap(bitmapByUrl);
                    SharedPreferences sp = getSharedPreferences("durationandformat",
                            Context.MODE_PRIVATE);
                    String stringTime = sp.getString("format", "");
                    int index1 = stringTime.indexOf(":");
                    int index2 = stringTime.indexOf(":", index1 + 1);
                    int hh = Integer.parseInt(stringTime.substring(0, index1));
                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
                    int formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
                    subformatTurnSecond = formatTurnSecond;
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String stringTime1 = getStringTime(subformatTurnSecond++);
                                    tv_daikao10.setText(stringTime1);
                                    SharedPreferences sp = getSharedPreferences("durationandformat",
                                            Context.MODE_PRIVATE);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("format", stringTime1);
                                    String firstandtime2 = getStringTime(firsttime1);
                                    edit.putString("firsttime", firstandtime2);
                                    edit.commit();

                                    LogUtils.e("format", stringTime1);
                                    LogUtils.e("firsttime", firstandtime2);

                                    if (stringTime1.equals(firstandtime2)) {
                                        timerTask.cancel();
                                        showUsersecondPopwindow(stringTime1);
                                    }

                                }
                            });
                        }
                    };
                    timer1.schedule(timerTask, 0, 1000);
                }
            }
        } else  // 根据返回码的不同，设置参数
            if (requestCode == 1) {
                if (resultCode == 1) {
                    if (url != null && !TextUtils.isEmpty(url)) {
                        id_show_camera_iv1.setContentDescription(url);
                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
                        id_show_camera_iv1.setImageBitmap(bitmapByUrl);
                        SharedPreferences sp = getSharedPreferences("durationandformat",
                                Context.MODE_PRIVATE);
                        String stringTime = sp.getString("format", "");
                        int index1 = stringTime.indexOf(":");
                        int index2 = stringTime.indexOf(":", index1 + 1);
                        int hh = Integer.parseInt(stringTime.substring(0, index1));
                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
                        int formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
                        subformatTurnThird = formatTurnSecond;
                        timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String stringTime2 = getStringTime(subformatTurnThird++);
                                        tv_daikao10.setText(stringTime2);
                                        SharedPreferences sp = getSharedPreferences("durationandformat",
                                                Context.MODE_PRIVATE);
                                        SharedPreferences.Editor edit = sp.edit();
                                        edit.putString("format", stringTime2);
                                        edit.commit();
                                        int qpLength = sp.getInt("qpLength", 0);
                                        int qpLengthtime = qpLength * 60;
                                        String qpLengthtime1 = getStringTime(qpLengthtime);
                                        LogUtils.e("累计时间", qpLengthtime1);


                                        if (stringTime2.equals(qpLengthtime1)) {
                                            timerTask.cancel();
                                            edit.putString("format", stringTime2);
                                            edit.commit();
                                            showUserthreePopwindow(stringTime2);
                                            subDaiKaoAdapter.notifyDataSetChanged();
                                        }
                                    }
                                });
                            }
                        };
                        timer1.schedule(timerTask, 0, 1000);
//                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                            Context.MODE_PRIVATE);
//                    String stringTime = sp.getString("format", "");
//                    int index1 = stringTime.indexOf(":");
//                    int index2 = stringTime.indexOf(":", index1 + 1);
//                    int hh = Integer.parseInt(stringTime.substring(0, index1));
//                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                    int    formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                    subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                    timerTask = new TimerTask() {
//                        @Override
//                        public void run() {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    String stringTime1 = getStringTime(subformatTurnSecond++);
//                                    tv_cumulativeLength.setText(stringTime1);
//
//                                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                                            Context.MODE_PRIVATE);
//                                    SharedPreferences.Editor edit = sp.edit();
//                                    edit.putString("format", stringTime1);
//                                    edit.commit();
//                                    int courseLength = sp.getInt("courseLength", 0);
//                                    int courseLengthtime = courseLength * 60;
//                                    String courseLengthtime1 = getStringTime(courseLengthtime);
//                                    LogUtils.e("累计时间",courseLengthtime1);
//                                    if(stringTime1.equals(courseLengthtime1))
//                                    {
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        timerTask.cancel();
//
//                                    }
//
//                                }
//                            });
//                        }
//                    };
//                    timer1.schedule(timerTask,0,1000);


//                    if(show_camera_iv.getDrawable() == null)
//                    {
//                        show_camera_iv.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv.setImageBitmap(bitmapByUrl);
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        String stringTime = sp.getString("format", "");
//                        int index1 = stringTime.indexOf(":");
//                        int index2 = stringTime.indexOf(":", index1 + 1);
//                        int hh = Integer.parseInt(stringTime.substring(0, index1));
//                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                        int    formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                        subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                        timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        String stringTime1 = getStringTime(subformatTurnSecond++);
//                                        tv_cumulativeLength.setText(stringTime1);
//                                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                                Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        String duration = sp.getString("duration", "");
//
//                                        if(stringTime1.equals(duration))
//                                        {
//                                            timerTask.cancel();
//
//                                            startActivityForResult(TakePhotoActivity.class,null, 0);
//                                        }
//
//                                    }
//                                });
//                            }
//                        };
//                        timer1.schedule(timerTask,0,1000);
//
//
//                    }else{
//                        show_camera_iv1.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv1.setImageBitmap(bitmapByUrl);
//
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        String stringTime = sp.getString("format", "");
//                        int index1 = stringTime.indexOf(":");
//                        int index2 = stringTime.indexOf(":", index1 + 1);
//                        int hh = Integer.parseInt(stringTime.substring(0, index1));
//                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                        int  formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                        subformatTurnSecond = formatTurnSecond - 2;
//                        timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        String stringTime1 = getStringTime(subformatTurnSecond++);
//                                        tv_cumulativeLength.setText(stringTime1);
//                                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                                Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                    }
//                                });
//                            }
//                        };
//                        timer1.schedule(timerTask,0,1000);
//                    }
                    }
                }
            } else  // 根据返回码的不同，设置参数
                if (requestCode == 2) {
                    if (resultCode == 1) {
                        if (url != null && !TextUtils.isEmpty(url)) {
                            id_show_camera_iv2.setContentDescription(url);
                            Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
                            id_show_camera_iv2.setImageBitmap(bitmapByUrl);
                            SharedPreferences sp = getSharedPreferences("durationandformat",
                                    Context.MODE_PRIVATE);
                            String stringTime = sp.getString("format", "");
                            int index1 = stringTime.indexOf(":");
                            int index2 = stringTime.indexOf(":", index1 + 1);
                            int hh = Integer.parseInt(stringTime.substring(0, index1));
                            int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
                            int ss = Integer.parseInt(stringTime.substring(index2 + 1));
                            int formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
                            subformatTurnFour = formatTurnSecond;
                            timerTask = new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            String stringTime3 = getStringTime(subformatTurnFour++);
                                            tv_daikao10.setText(stringTime3);
                                            SharedPreferences sp = getSharedPreferences("durationandformat",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.putString("format", stringTime3);
                                            edit.commit();
                                            int qpLength = sp.getInt("qpLength", 0);
                                            int qpLengthtime = qpLength * 60;
                                            String qpLengthtime1 = getStringTime(qpLengthtime);
                                            LogUtils.e("累计时间", qpLengthtime1);


                                            if (stringTime3.equals(qpLengthtime1)) {
                                                timerTask.cancel();
                                                edit.putString("format", stringTime3);
                                                edit.commit();
                                                subDaiKaoAdapter.notifyDataSetChanged();

                                            }

                                        }
                                    });
                                }
                            };
                            timer1.schedule(timerTask, 0, 1000);
//                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                            Context.MODE_PRIVATE);
//                    String stringTime = sp.getString("format", "");
//                    int index1 = stringTime.indexOf(":");
//                    int index2 = stringTime.indexOf(":", index1 + 1);
//                    int hh = Integer.parseInt(stringTime.substring(0, index1));
//                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                    int    formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                    subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                    timerTask = new TimerTask() {
//                        @Override
//                        public void run() {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    String stringTime1 = getStringTime(subformatTurnSecond++);
//                                    tv_cumulativeLength.setText(stringTime1);
//
//                                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                                            Context.MODE_PRIVATE);
//                                    SharedPreferences.Editor edit = sp.edit();
//                                    edit.putString("format", stringTime1);
//                                    edit.commit();
//                                    int courseLength = sp.getInt("courseLength", 0);
//                                    int courseLengthtime = courseLength * 60;
//                                    String courseLengthtime1 = getStringTime(courseLengthtime);
//                                    LogUtils.e("累计时间",courseLengthtime1);
//                                    if(stringTime1.equals(courseLengthtime1))
//                                    {
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        timerTask.cancel();
//
//                                    }
//
//                                }
//                            });
//                        }
//                    };
//                    timer1.schedule(timerTask,0,1000);


//                    if(show_camera_iv.getDrawable() == null)
//                    {
//                        show_camera_iv.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv.setImageBitmap(bitmapByUrl);
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        String stringTime = sp.getString("format", "");
//                        int index1 = stringTime.indexOf(":");
//                        int index2 = stringTime.indexOf(":", index1 + 1);
//                        int hh = Integer.parseInt(stringTime.substring(0, index1));
//                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                        int    formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                        subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                        timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        String stringTime1 = getStringTime(subformatTurnSecond++);
//                                        tv_cumulativeLength.setText(stringTime1);
//                                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                                Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        String duration = sp.getString("duration", "");
//
//                                        if(stringTime1.equals(duration))
//                                        {
//                                            timerTask.cancel();
//
//                                            startActivityForResult(TakePhotoActivity.class,null, 0);
//                                        }
//
//                                    }
//                                });
//                            }
//                        };
//                        timer1.schedule(timerTask,0,1000);
//
//
//                    }else{
//                        show_camera_iv1.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv1.setImageBitmap(bitmapByUrl);
//
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        String stringTime = sp.getString("format", "");
//                        int index1 = stringTime.indexOf(":");
//                        int index2 = stringTime.indexOf(":", index1 + 1);
//                        int hh = Integer.parseInt(stringTime.substring(0, index1));
//                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                        int  formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                        subformatTurnSecond = formatTurnSecond - 2;
//                        timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        String stringTime1 = getStringTime(subformatTurnSecond++);
//                                        tv_cumulativeLength.setText(stringTime1);
//                                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                                Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                    }
//                                });
//                            }
//                        };
//                        timer1.schedule(timerTask,0,1000);
//                    }
                        }
                    }
                }
    }

    private void showUseronePopwindow(final String stringTime) {
        //设置contentView
        View contentView = LayoutInflater.from(DaiKaoActivity.this).inflate(R.layout.test_popwindowlayout, null);
        mUserOnePopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        ImageView takepciture = (ImageView) contentView.findViewById(R.id.img_photo1);//点拍照
        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture1);//跟布局
        mUserOnePopWindow.setFocusable(false);
        mUserOnePopWindow.setOutsideTouchable(false);
        mUserOnePopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);


        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUserOnePopWindow.dismiss();
                String firsttimesub = stringTime.substring(3, 8);//截取字符串00:00:00变成00:00
                Bundle bundle = new Bundle();
                bundle.putInt("daikaosn", sn);
                bundle.putString("snapTime", firsttimesub);
                startActivityForResult(TakePhotoScrollsActivity.class, bundle, 0);

            }
        });

    }

    private void showUsersecondPopwindow(final String stringTime1) {
        //设置contentView
        View contentView = LayoutInflater.from(DaiKaoActivity.this).inflate(R.layout.test_popwindowlayout, null);
        mUserSecondPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        ImageView takepciture = (ImageView) contentView.findViewById(R.id.img_photo1);//点拍照
        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture1);//跟布局
        mUserSecondPopWindow.setFocusable(false);
        mUserSecondPopWindow.setOutsideTouchable(false);
        mUserSecondPopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);


        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUserSecondPopWindow.dismiss();
                String firsttimesub = stringTime1.substring(3, 8);//截取字符串00:00:00变成00:00
                Bundle bundle = new Bundle();
                bundle.putInt("daikaosn", sn);
                bundle.putString("snapTime", firsttimesub);
                startActivityForResult(TakePhotoScrollsActivity.class, bundle, 1);
            }
        });

    }

    private void showUserthreePopwindow(final String stringTime2) {
        //设置contentView
        View contentView = LayoutInflater.from(DaiKaoActivity.this).inflate(R.layout.test_popwindowlayout, null);
        mUserSecondPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        ImageView takepciture = (ImageView) contentView.findViewById(R.id.img_photo1);//点拍照
        final LinearLayout le_takepicture = (LinearLayout) contentView.findViewById(R.id.le_takepicture1);//跟布局
        mUserSecondPopWindow.setFocusable(false);
        mUserSecondPopWindow.setOutsideTouchable(false);
        mUserSecondPopWindow.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);
        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUserSecondPopWindow.dismiss();
                String firsttimesub = stringTime2.substring(3, 8);//截取字符串00:00:00变成00:00
                Bundle bundle = new Bundle();
                bundle.putInt("daikaosn", sn);
                bundle.putString("snapTime", firsttimesub);
                startActivityForResult(TakePhotoScrollsActivity.class, bundle, 2);
            }
        });

    }


    @Override
    public void requestData() {

        OkGo.get(AppInterfaceConfig.BASE_URL + "course/paper/" + qpsn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        DaiKaoCourseBean daiKaoCourseBean = JSON.parseObject(result, DaiKaoCourseBean.class);
                        DaiKaoCourseBean.DataBean data = daiKaoCourseBean.getData();

                        if (data == null) {
                            return;
                        }

                        String qptName = data.getQptName();//试卷种类名称

                        String qpName = data.getQpName();//试卷名称

                        int questionNo = data.getQuestionNo();//测验题数
                        int totalScore = data.getTotalScore();//总分
                        int passScore = data.getPassScore();//及格分
                        //试卷时长
                        int qpLength = data.getQpLength();
                        SharedPreferences sp = getSharedPreferences("durationandformat",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putInt("qpLength", qpLength);
                        edit.commit();
                        tv_qptName.setText("试卷种类：" + qptName);
                        tv_qpName.setText("试卷名称：" + qpName);
                        tv_questionNo.setText("试卷题数：" + questionNo);
                        tv_totalScore.setText("总分数：" + totalScore);
                        tv_passScore.setText("及格分数：" + passScore);
                        tv_shizhang.setText("试卷时长：" + qpLength + "分钟");


                    }
                });

//待考试卷详情
        new Login().getDaikao(sn, 1, 1000, this, 1);


    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {
            DaikaoAndHavetestCourseBean courseBean = JSON.parseObject(result, DaikaoAndHavetestCourseBean.class);
            List<DaikaoAndHavetestCourseBean.RowsBean> rowslist = courseBean.getRows();
            testlist.clear();
            testlist.addAll(rowslist);


            for (int i = 0; i < testlist.size(); i++) {
                DaikaoAndHavetestCourseBean.RowsBean temp = testlist.get(i);
                temp.setSeqNo(i + 1);
            }
            if (testlist.size() == 0) {
                customView.setVisibility(View.GONE);
                return;
            }
            customView.setCount(testlist.size());
            subDaiKaoAdapter = new SubDaiKaoAdapter(DaiKaoActivity.this, testlist, R.layout.daikao_itemn);
            lv_daikao.setAdapter(subDaiKaoAdapter);

        } else if (what == 2) {
            SharedPreferences sp = getSharedPreferences("score",
                    Context.MODE_PRIVATE);
            float score = sp.getFloat("score", 0);
            TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
            builder.setMessage("您此次考得" + score + "分不及格");
            builder.setTitle("提示:");
            builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask = null;
                    timer1 = null;
                    SharedPreferences sp = getSharedPreferences("score",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                    SharedPreferences spp = getSharedPreferences("durationandformat",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit1 = spp.edit();
                    edit1.clear();
                    edit1.commit();
                    finish();
                }
            });
            builder.create().show();


        } else if (what == 3) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            if (code == 0) {
//                    LemonHello.getSuccessHello("提示", "成功")
//                            .addAction(new LemonHelloAction("我知道啦", new LemonHelloActionDelegate() {
//                                @Override
//                                public void onClick(LemonHelloView helloView, LemonHelloInfo helloInfo, LemonHelloAction helloAction) {
//                                    helloView.hide();
//                                }
//                            }))
//                            .show(DaiKaoActivity.this);
            }
        } else if (what == 4) {
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            String userName = data.getUserName();
            String userMobile = data.getUserMobile();

            if (userName == null) {
                tv_usename.setText("姓    名：");

            } else {
                tv_usename.setText("姓    名：" + userName);
            }
            if (userMobile == null) {
                tv_phone.setText("手    机：");
            } else {
                tv_phone.setText("手    机：" + userMobile);
            }


            String idcNo = data.getIdcNo();

            if (idcNo == null) {
                tv_id.setText("身份证：");
            } else {

                tv_id.setText("身份证：" + idcNo);

            }

            tv_company.setText("企    业：" + orgName);
        }


        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if (what == 2) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
            builder.setMessage(msg);
            builder.setTitle("提示:");
            builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            });
            builder.create().show();
        } else if (what == 3) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
            builder.setMessage(msg);
            builder.setTitle("提示:");
            builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            });
            builder.create().show();

        }

        super.onError(result, call, response, what);
    }


    /**
     * 保存图片
     */
    private void save(File fileDir) {
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        final String fileName = simpleDateFormat.format(new Date()) + ".png";
        File savefile = new File(fileDir, fileName);
        final String filePath = getFilePath(fileDir);
        if (signatureview.getTouched()) {//是否签名

            try {
                signatureview.save(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            uploadImg(savefile);//上传服务器封装方法

            //  Toast.makeText(SignActivity.this,"上传成功",Toast.LENGTH_LONG).show();
        } else {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(DaiKaoActivity.this);
            builder1.setMessage("请完善您的签名");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private void uploadImg(File mediaFile) {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("psignImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("sn", sn + "");
            builder.addFormDataPart("reSubmitMark", 0 + "");
        }
        MultipartBody requestBody = builder.build();
        mProgressDialog = new ProgressDialog(DaiKaoActivity.this, ProgressDialog.THEME_HOLO_DARK);
        mProgressDialog.setMessage("提交中...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "app/paper/finishForT")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
                mProgressDialog.dismiss();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                DaiKaoSureBean sureBean = JSON.parseObject(str, DaiKaoSureBean.class);
                DaiKaoSureBean.DataBean data = sureBean.getData();
                int passMark = data.getPassMark();
                float score = data.getScore();
                int testNo = data.getTestNo();
                mProgressDialog.dismiss();
                if (passMark == 1) {
                    Looper.prepare();
                    TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                    builder.setMessage("您此次考得" + score + "分及格");
                    builder.setTitle("提示:");
                    builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            timerTask.cancel();
                            timer1.cancel();
                            timerTask = null;
                            timer1 = null;
                            SharedPreferences sp = getSharedPreferences("score",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.clear();
                            edit.commit();
                            SharedPreferences spp = getSharedPreferences("durationandformat",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit1 = spp.edit();
                            edit1.clear();
                            edit1.commit();
                            finish();

                        }
                    });
                    builder.create().show();
                    Looper.loop();
                } else {
                    if (testNo > 1) {
                        Looper.prepare();
                        TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                        builder.setMessage("您此次考得" + score + "分不及格");
                        builder.setTitle("提示:");
                        builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                timerTask.cancel();
                                timer1.cancel();
                                timerTask = null;
                                timer1 = null;
                                SharedPreferences sp = getSharedPreferences("score",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit = sp.edit();
                                edit.clear();
                                edit.commit();
                                SharedPreferences spp = getSharedPreferences("durationandformat",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit1 = spp.edit();
                                edit1.clear();
                                edit1.commit();
                                finish();

                            }
                        });
                        builder.create().show();
                        Looper.loop();
                    } else if (testNo == 1) {
                        Looper.prepare();
                        //initBuKao();
                        SharedPreferences sp = getSharedPreferences("score",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putFloat("score", score);
                        edit.commit();

                        Looper.loop();
                    } else if (testNo == 0) {
                        Looper.prepare();
                        TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                        builder.setMessage("您此次考得" + score + "分不及格");
                        builder.setTitle("提示:");
                        builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                timerTask.cancel();
                                timer1.cancel();
                                timerTask = null;
                                timer1 = null;
                                SharedPreferences sp = getSharedPreferences("score",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit = sp.edit();
                                edit.clear();
                                edit.commit();
                                SharedPreferences spp = getSharedPreferences("durationandformat",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit1 = spp.edit();
                                edit1.clear();
                                edit1.commit();
                                finish();

                            }
                        });
                        builder.create().show();
                        Looper.loop();
                    }

                }
//                mProgressDialog.dismiss();
//                finish();
            }
        });

    }

    //补考接口
    private void initBuKao() {
        new Login().getBukao(sn, this, 2);
    }

    /**
     * 保存图片
     */
    private void saveSecond(File fileDir) {
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        final String fileName = simpleDateFormat.format(new Date()) + ".png";
        File savefile = new File(fileDir, fileName);
        final String filePath = getFilePath(fileDir);
        if (signatureview.getTouched()) {//是否签名

            try {
                signatureview.save(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            uploadImgsaveSecond(savefile);//上传服务器封装方法

            //  Toast.makeText(SignActivity.this,"上传成功",Toast.LENGTH_LONG).show();
        } else {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(DaiKaoActivity.this);
            builder1.setMessage("请完善您的签名");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
    }

    //    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
//    private final OkHttpClient client = new OkHttpClient();
    private void uploadImgsaveSecond(File mediaFile) {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("psignImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("sn", sn + "");
            builder.addFormDataPart("reSubmitMark", 1 + "");
        }
        MultipartBody requestBody = builder.build();
        mProgressDialog = new ProgressDialog(DaiKaoActivity.this, ProgressDialog.THEME_HOLO_DARK);
        mProgressDialog.setMessage("提交中...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "app/paper/finishForT")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
                mProgressDialog.dismiss();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                DaiKaoSureBean sureBean = JSON.parseObject(str, DaiKaoSureBean.class);
                DaiKaoSureBean.DataBean data = sureBean.getData();
                int passMark = data.getPassMark();
                float score = data.getScore();
                mProgressDialog.dismiss();
                if (passMark == 1) {
                    Looper.prepare();
                    TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                    builder.setMessage("您此次考得" + score + "分及格");
                    builder.setTitle("提示:");
                    builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            timerTask.cancel();
                            timer1.cancel();
                            timerTask = null;
                            timer1 = null;
                            SharedPreferences sp = getSharedPreferences("score",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.clear();
                            edit.commit();
                            SharedPreferences spp = getSharedPreferences("durationandformat",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit1 = spp.edit();
                            edit1.clear();
                            edit1.commit();
                            finish();

                        }
                    });
                    builder.create().show();
                    Looper.loop();
                } else {


                    SharedPreferences sp = getSharedPreferences("durationandformat",
                            Context.MODE_PRIVATE);
                    String format = sp.getString("format", "");
                    int qpLength = sp.getInt("qpLength", 0);
                    int qpLengthtime = qpLength * 60;
                    String[] splitformat = format.split(":");
                    String format1 = splitformat[0];
                    String format2 = splitformat[1];
                    String format3 = splitformat[2];
                    int iformat1 = Integer.valueOf(format1);//转int
                    int iformat2 = Integer.valueOf(format2);//转int
                    int iformat3 = Integer.valueOf(format3);//转int
                    int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
                    if (qpLengthtime == formattime) {
                        Looper.prepare();
                        TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                        builder.setMessage("您此次考得" + score + "分不及格请继续作答");
                        builder.setTitle("提示:");
                        builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                timerTask.cancel();
                                timer1.cancel();
                                timerTask = null;
                                timer1 = null;
                                SharedPreferences sp = getSharedPreferences("score",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit = sp.edit();
                                edit.clear();
                                edit.commit();
                                SharedPreferences spp = getSharedPreferences("durationandformat",
                                        Context.MODE_PRIVATE);
                                SharedPreferences.Editor edit1 = spp.edit();
                                edit1.clear();
                                edit1.commit();
                                finish();

                            }
                        });
                        builder.create().show();
                        Looper.loop();
                    } else {

                        Looper.prepare();
                        TiShiDialog.Builder builder = new TiShiDialog.Builder(DaiKaoActivity.this);
                        builder.setMessage("您此次考得" + score + "分不及格请继续作答");
                        builder.setTitle("提示:");
                        builder.setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();


                            }
                        });
                        builder.create().show();
                        Looper.loop();
                    }

                }


            }
        });

    }

//    public void verifyStoragePermissions(Activity activity) {
//
//        try {
//            //检测是否有写的权限
//            int permission = ActivityCompat.checkSelfPermission(activity,
//                    "android.permission.WRITE_EXTERNAL_STORAGE");
//            if (permission != PackageManager.PERMISSION_GRANTED) {
//                // 没有写的权限，去申请写的权限，会弹出对话框
//                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 得到图片的路径 以及图片的名字
     */
    private String getFilePath(File fileDir) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        final String fileName = simpleDateFormat.format(new Date()) + ".png";
        LogUtils.e("filename", "---" + fileName);
        File file = new File(fileDir, fileName);
        return file.getAbsolutePath();
    }

    public class SubDaiKaoAdapter extends CommonAdapter<DaikaoAndHavetestCourseBean.RowsBean> {
        private Context context;
        private List<DaikaoAndHavetestCourseBean.RowsBean> mList;
        private LiumRadioGroup radioGroup;
        private RadioButton radioButtonA;
        private RadioButton radioButtonB;
        private RadioButton radioButtonC;
        private RadioButton radioButtonD;

        public SubDaiKaoAdapter(Context context, List<DaikaoAndHavetestCourseBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;
        }

        public void disableRadioGroup(LiumRadioGroup testRadioGroup) {
            testRadioGroup.clearCheck();
            for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
                final RadioButton radioButton = (RadioButton) testRadioGroup.getChildAt(i);
                radioButton.setEnabled(false);
                radioButton.setChecked(false);

            }
        }

        public void yesdisableRadioGroup(LiumRadioGroup testRadioGroup) {
            testRadioGroup.clearCheck();
            for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
                final RadioButton radioButton = (RadioButton) testRadioGroup.getChildAt(i);
                radioButton.setEnabled(true);
                radioButton.setChecked(true);

            }
        }

        @Override
        public void convert(ViewHolder holder, final DaikaoAndHavetestCourseBean.RowsBean item, final int positon) {

            TextView tv_questionDesc = holder.getView(R.id.tv_daikao_test);
            TextView tv_scon = holder.getView(R.id.tv_daikao_test2);
            ImageView img_daikao = holder.getView(R.id.img_daikao_test_item);
            tv_questionDesc.setText(mList.get(positon).getSeqNo() + ". " + mList.get(positon).getQuestionDesc());
            tv_scon.setText("分数：" + mList.get(positon).getScore() + "分");
            if (mList.get(positon).getUrl() == null) {
                img_daikao.setVisibility(View.GONE);

            } else {
                img_daikao.setVisibility(View.VISIBLE);
                if (mList.get(positon).getUrl().contains("aliyuncs.com")) {
                    Picasso.with(context).load(Uri.parse(mList.get(positon).getUrl())).placeholder(R.mipmap.no_data2).into(img_daikao);
                } else {

                    Picasso.with(context).load(Uri.parse(AppInterfaceConfig.getRequestUrl(mList.get(positon).getUrl()))).placeholder(R.mipmap.no_data2).into(img_daikao);
                }
            }


            final RelativeLayout re = (RelativeLayout) holder.getView(R.id.re_daikao2);
            radioGroup = (LiumRadioGroup) holder.getView(R.id.rg);
            radioButtonA = (RadioButton) radioGroup.findViewById(R.id.radioButton_daikao);
            radioButtonB = (RadioButton) radioGroup.findViewById(R.id.radioButton_daikao1);
            radioButtonC = (RadioButton) radioGroup.findViewById(R.id.radioButton_daikao2);
            radioButtonD = (RadioButton) radioGroup.findViewById(R.id.radioButton_daikao3);
            String OptionA = mList.get(positon).getOptionA();
            if (OptionA == null) {
                radioButtonA.setVisibility(View.GONE);
            } else {
                String OptionA1 = OptionA.toString().trim();
                if (OptionA1.length() == 0) {
                    radioButtonA.setVisibility(View.GONE);
                } else {
                    radioButtonA.setVisibility(View.VISIBLE);
                    radioButtonA.setText("A. " + OptionA1);
                }
            }
            String OptionB = mList.get(positon).getOptionB();
            if (OptionB == null) {
                radioButtonB.setVisibility(View.GONE);

            } else {
                String OptionB1 = OptionB.toString().trim();
                if (OptionB1.length() == 0) {
                    radioButtonB.setVisibility(View.GONE);
                } else {

                    radioButtonB.setVisibility(View.VISIBLE);
                    radioButtonB.setText("B. " + OptionB1);
                }
            }
            String OptionC = mList.get(positon).getOptionC();
            if (OptionC == null) {
                radioButtonC.setVisibility(View.GONE);

            } else {
                String OptionC1 = OptionC.toString().trim();
                if (OptionC1.length() == 0) {
                    radioButtonC.setVisibility(View.GONE);
                } else {
                    radioButtonC.setVisibility(View.VISIBLE);
                    radioButtonC.setText("C. " + OptionC1);
                }
            }

            String OptionD = mList.get(positon).getOptionD();
            if (OptionD == null) {

                radioButtonD.setVisibility(View.GONE);
            } else {
                String OptionD1 = OptionD.toString().trim();
                if (OptionD1.length() == 0) {
                    radioButtonD.setVisibility(View.GONE);
                } else {
                    radioButtonD.setVisibility(View.VISIBLE);
                    radioButtonD.setText("D. " + OptionD1);
                }
            }
            SharedPreferences sp = getSharedPreferences("durationandformat",
                    Context.MODE_PRIVATE);
            String format = sp.getString("format", "");
            int qpLength = sp.getInt("qpLength", 0);
            int qpLengthtime = qpLength * 60;
            String[] splitformat = format.split(":");
            String format1 = splitformat[0];
            String format2 = splitformat[1];
            String format3 = splitformat[2];
            int iformat1 = Integer.valueOf(format1);//转int
            int iformat2 = Integer.valueOf(format2);//转int
            int iformat3 = Integer.valueOf(format3);//转int
            int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
            if (formattime == qpLengthtime) {
                disableRadioGroup(radioGroup);
                re.setVisibility(View.VISIBLE);
                re.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(DaiKaoActivity.this);
                        builder1.setMessage("考试时间到了不能作答，请您点提交。");
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });

                        builder1.create().show();
                    }
                });

            }


            radioGroup.setOnCheckedChangeListener(null);
            switch (item.getChecked()) {
                case 1:

                    radioGroup.check(R.id.radioButton_daikao);
                    break;
                case 2:

                    radioGroup.check(R.id.radioButton_daikao1);
                    break;
                case 3:

                    radioGroup.check(R.id.radioButton_daikao2);
                    break;
                case 4:

                    radioGroup.check(R.id.radioButton_daikao3);
                    break;
                default:
                    radioGroup.clearCheck();
                    break;
            }

            radioGroup.setId(positon);
            radioGroup.setOnCheckedChangeListener(new LiumRadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(LiumRadioGroup group, int checkedId) {
                    item.setSelect(true);
                    int sn = mList.get(positon).getSn();
                    DaikaoAndHavetestCourseBean.RowsBean rowsBean = mList.get(group.getId());
                    SharedPreferences sp = getSharedPreferences("durationandformat",
                            Context.MODE_PRIVATE);
                    String format = sp.getString("format", "");
                    int qpLength = sp.getInt("qpLength", 0);
                    int qpLengthtime = qpLength * 60;
                    String[] splitformat = format.split(":");
                    String format1 = splitformat[0];
                    String format2 = splitformat[1];
                    String format3 = splitformat[2];
                    int iformat1 = Integer.valueOf(format1);//转int
                    int iformat2 = Integer.valueOf(format2);//转int
                    int iformat3 = Integer.valueOf(format3);//转int
                    int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;

                    if (checkedId == R.id.radioButton_daikao) {
                        if (formattime == qpLengthtime) {
                            return;
                        }
                        new Login().getDaikaoQuetion(sn, "A", (HttpListener) context, 3);
                        rowsBean.setChecked(1);
                    } else if (checkedId == R.id.radioButton_daikao1) {
                        if (formattime == qpLengthtime) {
                            return;
                        }
                        new Login().getDaikaoQuetion(sn, "B", (HttpListener) context, 3);
                        rowsBean.setChecked(2);
                    } else if (checkedId == R.id.radioButton_daikao2) {
                        if (formattime == qpLengthtime) {
                            return;
                        }
                        new Login().getDaikaoQuetion(sn, "C", (HttpListener) context, 3);
                        rowsBean.setChecked(3);
                    } else if (checkedId == R.id.radioButton_daikao3) {
                        if (formattime == qpLengthtime) {
                            return;
                        }
                        new Login().getDaikaoQuetion(sn, "D", (HttpListener) context, 3);
                        rowsBean.setChecked(4);
                    }
                }
            });

        }
    }
}
